package redis

import (
	"context"
	"fmt"
	"shop_srv/shop"
	"strconv"
)

func AddCart(cart map[string]interface{}) error {
	key := fmt.Sprintf("cart:user_id_%d:good_id_%d", cart["user_id"], cart["good_id"])
	return Rdb.HMSet(context.Background(), key, cart).Err()
}

func CartExist(userId, goodId int64) bool {
	key := fmt.Sprintf("cart:user_id_%d:good_id_%d", userId, goodId)
	return Rdb.Exists(context.Background(), key).Val() == 1
}

func UpdateNumBy(userId, goodId, num int64) error {
	key := fmt.Sprintf("cart:user_id_%d:good_id_%d", userId, goodId)
	return Rdb.HIncrBy(context.Background(), key, "good_num", num).Err()
}

func GetCart(UserId int64) (cartList []*shop.CartItem, err error) {
	key := fmt.Sprintf("cart:user_id_%d:*", UserId)
	keys := Rdb.Keys(context.Background(), key).Val()
	fmt.Println(keys)
	for _, s := range keys {
		goodMap := Rdb.HGetAll(context.Background(), s).Val()
		userId, _ := strconv.Atoi(goodMap["user_id"])
		goodId, _ := strconv.Atoi(goodMap["good_id"])
		num, _ := strconv.Atoi(goodMap["good_num"])
		goodPrice, _ := strconv.ParseFloat(goodMap["good_price"], 64)

		cartList = append(cartList, &shop.CartItem{
			GoodTitle: goodMap["good_title"],
			GoodPrice: float32(goodPrice),
			UserId:    int64(userId),
			GoodId:    int64(goodId),
			Num:       int64(num),
		})
	}
	return
}
